package com.yonyou.brigade.third_parties.bfjr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.order_center.service.IBriOrderService;
import com.yonyou.brigade.third_parties.bfjr.constant.BfjrConstant;
import com.yonyou.brigade.third_parties.bfjr.service.IBfjrOrderService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

@Service
public class BfjrOrderServiceImpl implements IBfjrOrderService {
    private static Logger logger = LoggerFactory.getLogger(BfjrOrderServiceImpl.class);

    @Value("${bfjr.url.getOrderList}")
    private String bfjrGetOrderUrl;

    @Value("${bfjr.tradeFlightType}")
    private String bfjrTradeFlightType;

    @Value("${bfjr.tradeHotelType}")
    private String bfjrTradeHotelType;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.register.userId}")
    private String cnvRegisterUserId;

    @Value("${cnv.register.tenant}")
    private String cnvRegisterTenant;

    @Value("${cnv.register.cookie}")
    private String cnvRegisterCookie;

    @Autowired
    private IMongoDao mongoDao;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService convertService;

    @Autowired
    @Qualifier("briOrderServiceImpl")
    private IBriOrderService briOrderService;


    @Override
    public void getBrjrOrderList(String appId, Map param,String tenant,Integer channelId) {
        JSONObject requestParam = new JSONObject(param);
        requestParam.put("appId",appId);
        logger.info("北方假日机票酒店订单查询" + requestParam.toJSONString());
        String flightOrderResultString = HttpClientUtil.doPostJsonForm(bfjrGetOrderUrl, requestParam.toJSONString());
        logger.info("北方假日机票酒店订单查询结果" + flightOrderResultString);
        if (StringUtil.isNotEmpty(flightOrderResultString)){
            JSONObject orderJSONObject = JSONObject.parseObject(flightOrderResultString);
            String ret = orderJSONObject.getString("ret");
            if (orderJSONObject == null && ret == "1") {
                logger.error("北方假日机票酒店订单查询请求失败，请求参数param:+param,请求结果：" + flightOrderResultString);
            } else {
                JSONArray flightOrderList = orderJSONObject.getJSONArray("flightOrderList");
                if (flightOrderList != null && flightOrderList.size() > 0) {
                    for (int i = 0; i < flightOrderList.size(); i++) {
                        JSONObject flightOrder = flightOrderList.getJSONObject(i);
                        // 订单转换与保存
                        doBfjrFlightOrderConvertAndSave(flightOrder, tenant, channelId);
                    }
                }

                JSONArray hotelOrderList = orderJSONObject.getJSONArray("hotelOrderList");
                if (hotelOrderList != null && hotelOrderList.size() > 0) {
                    for (int i = 0; i < hotelOrderList.size(); i++) {
                        JSONObject hotelOrder = hotelOrderList.getJSONObject(i);
                        // 订单转换与保存
                        doBfjrHotelOrderConvertAndSave(hotelOrder, tenant, channelId);
                    }
                }

            }

        }
    }





    /**
     * 解析北方假日机票订单
     * @param
     */
        private void doBfjrFlightOrderConvertAndSave(JSONObject flightOrder, String tenant, int channelId) {
        JSONObject res;

                //机票订单处理

                //将成本中心列表中的成本中心名称放到psg乘机人列表
                String orderId = flightOrder.getString("orderId");

                JSONArray costCenterList = flightOrder.getJSONArray("costCenterList");
                JSONArray psgList = flightOrder.getJSONArray("psgList ");
                 if (costCenterList != null && costCenterList.size() > 0) {
                for (int i = 0; i <costCenterList.size() ; i++) {
                    JSONObject costJson = costCenterList.getJSONObject(i);
                    String typeName = costJson.getString("typeName");
                    for (int p = i; p < psgList.size(); p++) {
                        JSONObject  psgObject = psgList.getJSONObject(p);
                        if (typeName.equals(BfjrConstant.COMPANY_TYPE_NAME)) {
                            psgObject.put("companyCost",costJson.getString("costCenterName"));

                        } else if (typeName.equals(BfjrConstant.DEPT_TYPE_NAME)) {
                            psgObject.put("deptCost",costJson.getString("costCenterName"));

                        } else if (typeName.equals(BfjrConstant.PROJECT_TYPE_NAME)) {
                            psgObject.put("projectCost",costJson.getString("costCenterName"));

                        } else if (typeName.equals(BfjrConstant.FEE_TYPE_NAME)) {
                            psgObject.put("feeCost",costJson.getString("costCenterName"));
                        }
                        break;
                    }
                }
            }


                flightOrder.put("fromSource", ChannelEnum.BFJR.getName());
                dealWithMongo("flight", orderId, BfjrConstant.BFJR_FLIGHT_MONGO_ORDER_TABLENAME, flightOrder);
                res = convertService.convert(bfjrTradeFlightType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, flightOrder);
                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {

                                try {
                                    briOrderService.saveFlight(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (ParseException e) {
                                    logger.error("保存北方假日机票订单时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }

    }




    /**
     * 解析北方假日酒店订单
     * @param
     */
    private void doBfjrHotelOrderConvertAndSave(JSONObject hotelOrder, String tenant, int channelId) {
        JSONObject res;

        //火车票订单处理
        String orderId = hotelOrder.getString("orderId");
               /* if ("未提交".equals(orderStatus) || "已取消".equals(orderStatus)) {
                    continue;
                }*/
        hotelOrder.put("fromSource", ChannelEnum.BFJR.getName());
        dealWithMongo("hotel", orderId, BfjrConstant.BFJR_HOTEL_MONGO_ORDER_TABLENAME, hotelOrder);
        res = convertService.convert(bfjrTradeHotelType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, hotelOrder);
        if (res.getBoolean("success")) {
            JSONArray results = res.getJSONArray("result");
            if (results != null && results.size() > 0) {
                for (int j = 0; j < results.size(); j++) {
                    JSONObject jsonObject = results.getJSONObject(j);
                    JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                    if (orderCenter != null) {

                        try {
                            briOrderService.saveFlight(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                        } catch (ParseException e) {
                            logger.error("保存北方假日火车票订单时出现错误：channelId：" + channelId, e);
                        }
                    }
                }
            }
        }

    }




    private void dealWithMongo(String type, String orderId, String mongoName, JSONObject orderJson) {
        CriteriaMap criteriaMap = new CriteriaMap();
        if ("hotel".equals(type)) {
            criteriaMap.put("OrderID",orderId);
        } else if ("flight".equals(type) || "train".equals(type) || "car".equals(type)) {
            criteriaMap.put("BasicInfo.OrderID",orderId);
        } else if ("carQuick".equals(type)) {
            criteriaMap.put("BasicInfo.OrderId",orderId);
        } else if ("domPickUp".equals(type)) {
            criteriaMap.put("DomPickUpCarBasicInfo.OrderId",orderId);
        } else if ("domCharter".equals(type)) {
            criteriaMap.put("DomCharterCarBasicInfo.OrderId",orderId);
        }
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, mongoName);
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, mongoName);
            mongoDao.getMongoTemplate().save(orderJson, mongoName);
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson, mongoName);
        }
    }



}
